<!--
 * @Author: weikang
 * @Description:
 * @Date: 2023-12-22 22:47:46
 * @LastEditTime: 2025-06-13 20:49:39
 * @FilePath: \env-manager-pc\src\views\document\manager\index.vue
-->
<script setup lang="ts">
import { ElMessage, ElMessageBox } from 'element-plus'
import { isEmpty } from 'lodash-es'
import apiEnt from '@/api/modules/ent'
import { usePage } from '@/utils/commonHook'
import { useEnvOrgs, useGetNEIndustrys, useOwnerOrgs } from '@/utils/dataHook'
import { QueryObj } from '@/utils/dataHook/data'
import useKeepAliveStore from '@/store/modules/keepAlive'
import useUserStore from '@/store/modules/user'
import documentApi from '@/api/modules/document.ts'

defineOptions({
  name: 'DocumentManagerList',
  beforeRouteEnter(to, from, next) {
    next((vm) => {
      const names = ['document-manager-modify', 'document-manager-create']
      if (names.includes(from.name as string)) {
        const instance = vm as any
        instance.getTableData()
      }
    })
  },
})

const userStore = useUserStore()

const isEnterpris = userStore.isEnterpris

const keepAliveStore = useKeepAliveStore()

onBeforeRouteLeave((to) => {
  const names = ['document-manager-detail', 'document-manager-modify', 'document-manager-create']
  if (names.includes(to.name as string)) {
    keepAliveStore.add('DocumentManagerList')
  }
  else {
    keepAliveStore.remove('DocumentManagerList')
  }
})

const router = useRouter()
const route = useRoute()
const loading = ref(false)

const tableData = ref<any[]>([])
const { page, pageNumChange, pageSizeChange } = usePage(getTableData)

const searchData = reactive(new QueryObj({
  objType: 'DIM.Business.Enterprise',
  Filters: ['DIM.Business.Envs.EnterpriseFilters.EnvOrgGUIDFilter', 'DIM.Units.Filters.NameFilter', 'DIM.Units.Filters.OwnerOrgGUIDFilter', 'DIM.Business.EnterpriseFilters.NEICodeFilter'],
}))

if (!isEmpty(route.query)) {
  Object.keys(route.query).forEach((key) => {
    searchData[key] = route.query[key]
  })
  search()
}

function search() {
  page.PageNum = 1
  getTableData()
}

async function getTableData() {
  loading.value = true
  const res = await apiEnt.GetEnterpriseAndDeviceNums({
    objFilter: searchData.getQuery(),
    pageSize: page.PageSize,
    pageNum: page.PageNum,
  })
  loading.value = false
  // console.log('%c [ res ]-27', 'font-size:13px; background:pink; color:#bf2c9f;', res)
  const { Rows, RecordsetCount } = res
  tableData.value = Rows || []
  page.RecordsetCount = RecordsetCount
}

getTableData()

function toCreate() {
  router.push('/document/manager/create')
}
function toEdit(row: any) {
  router.push(`/document/manager/modify/${row.EntObjID}`)
}
function toDetail(row: any) {
  router.push(`/document/manager/detail/${row.EntObjID}`)
}

function toOutput() {
  ElMessage.info('正在导出，请稍等...')
  documentApi.GetEnterpriseAndDeviceNumsToExcel({
    objFilter: searchData.getQuery(),
    pageSize: page.PageSize,
    pageNum: page.PageNum,
  }).then((res) => {
    const url = window.URL.createObjectURL(res as Blob)
    const a = document.createElement('a')
    a.href = url
    a.target = '_blank'
    a.click()
  }).catch(() => {
    ElMessage.error('导出失败，请重试。')
  })
}

const OwnerList = isEnterpris ? [] : useOwnerOrgs()
const industryList = isEnterpris ? [] : useGetNEIndustrys()
const envOrgs = isEnterpris ? [] : useEnvOrgs()
const defaultProps = {
  children: 'Children',
  label: 'Name',
}

async function delEnt(row: any) {
  await ElMessageBox.confirm(
    `确认删除企业 ${row.EntName} 吗？`,
    '删除',
    {
      type: 'warning',
    },
  )
  await apiEnt.entDelete({
    enterpriseObjID: row.EntObjID,
  })
  ElMessage.success('删除成功')
  getTableData()
}

defineExpose({
  getTableData,
})
</script>

<template>
  <div>
    <PageHeader>
      <template #content>
        <ElForm label-width="100">
          <ElRow>
            <ElCol v-if="!isEnterpris" :span="6">
              <ElFormItem label="管理机构">
                <el-tree-select
                  v-model="searchData['DIM.Business.Envs.EnterpriseFilters.EnvOrgGUIDFilter']"
                  value-key="Code"
                  :data="envOrgs"

                  :render-after-expand="false"
                  :props="defaultProps"
                  clearable check-strictly
                  class="w-full"
                />
              </ElFormItem>
            </ElCol>
            <ElCol :span="6">
              <ElFormItem label="企业名称">
                <ElInput v-model="searchData['DIM.Units.Filters.NameFilter']" clearable placeholder="请输入" />
              </ElFormItem>
            </ElCol>
            <ElCol v-if="!isEnterpris" :span="6">
              <ElFormItem label="运维公司">
                <el-tree-select
                  v-model="searchData['DIM.Units.Filters.OwnerOrgGUIDFilter']"
                  value-key="Code"
                  :data="OwnerList"
                  check-strictly
                  :render-after-expand="false"
                  :props="defaultProps"
                  clearable
                  class="w-full"
                />
              </ElFormItem>
            </ElCol>
            <ElCol v-if="!isEnterpris" :span="6">
              <ElFormItem label="行业">
                <el-tree-select
                  v-model="searchData['DIM.Business.EnterpriseFilters.NEICodeFilter']"
                  value-key="Code"
                  :data="industryList"
                  check-strictly
                  :render-after-expand="false"
                  :props="defaultProps"
                  class="w-full"
                  clearable
                />
              </ElFormItem>
            </ElCol>
            <ElCol :span="6" :push="isEnterpris ? 12 : 18" class="flex flex-justify-end">
              <ElButton type="primary" class="mr-[10px]" @click="search">
                查询
              </ElButton>
              <Auth value="/document/manager/create">
                <ElButton class="mr-[10px]" type="success" @click="toCreate">
                  新增
                </ElButton>
              </Auth>
              <ElButton type="warning" @click="toOutput">
                导出
              </ElButton>
            </ElCol>
          </ElRow>
        </ElForm>
      </template>
    </PageHeader>
    <PageMain>
      <div v-auto-height="85">
        <vxe-table
          auto-resize border
          height="100%"
          :data="tableData"
          :loading="loading"
          :row-config="{ isCurrent: true }"
        >
          <VxeColumn type="seq" title="序号" width="80" />
          <VxeColumn field="EnvOrgName" title="管理机构" min-width="100" show-overflow />
          <VxeColumn field="OwnerOrgName" title="运维公司" min-width="100" show-overflow />
          <VxeColumn field="EntName" title="企业名称" min-width="100" show-overflow />
          <VxeColumn field="NEIndustryName" title="行业" width="150" show-overflow />
          <vxe-colgroup title="监测点">
            <VxeColumn field="EntAllDevNum" title="合计" width="100" />
            <VxeColumn field="EntTotalDevNum" title="总表" width="100" />
            <VxeColumn field="ProduceDevNum" title="产污" width="100" />
            <VxeColumn field="ReuseDevNum" title="治理" width="100" />
          </vxe-colgroup>
          <VxeColumn field="operate" title="操作" width="160" fixed="right">
            <template #default="{ row }">
              <div class="flex">
                <Auth value="/document/manager/detail/:id">
                  <ElButton class="mr-[10px]" type="primary" link @click="toDetail(row)">
                    查看
                  </ElButton>
                </Auth>
                <Auth v-if="!isEnterpris" value="/document/manager/modify/:id">
                  <ElButton type="success" link @click="toEdit(row)">
                    编辑
                  </ElButton>
                  <ElButton type="danger" link @click="delEnt(row)">
                    删除
                  </ElButton>
                </Auth>
              </div>
            </template>
          </VxeColumn>
        </vxe-table>
      </div>
      <ElPagination
        class="mt-4"
        :page-size="page.PageSize"
        :total="page.RecordsetCount"
        :current-page="page.PageNum"
        layout="total, sizes, prev, pager, next, jumper"
        :page-sizes="[20, 50, 100]"
        @current-change="pageNumChange"
        @size-change="pageSizeChange"
      />
    </PageMain>
  </div>
</template>
